<template>
  <section class="grant-main">
    <el-collapse-transition>
      <section class="main-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="listQuery.giveName"
          placeholder="输入福利名称搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <section class="search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </section>
      </section>
    </el-collapse-transition>

    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>平台商城福利配置</span>
      </section>
      <section class="main-buttons-btns">
        <el-button style="margin-left: 10px" @click="handleCreate">新建</el-button>
      </section>
    </section>

    <section class="main-tab">
      <el-tabs v-model="active" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in types" :key="item.id" :label="item.name" :name="item.id" />
      </el-tabs>
      <!-- 	<div class="tabs">
				<div @click="handleTabClick2(item)" v-for="(item,index) in types" :key="item.id" class="tabItem" :class="{'choose':active==item.id,'leng':item.name.length>5} ">{{item.name}}</div>
			</div> -->
    </section>

    <section class="main-table">
      <v-table
        :list="list"
        :tag="'grantmain' + active"
        :list-loading="listLoading"
        :filter-column="filtercolumn"
        @handleSelectionChange="handleSelectionChange"
      >
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          min-width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleStatus(scope.row)">
              {{ scope.row.publishStatus == "GIPSTSTUS01" ? "取消发布" : "发布" }}</el-button>
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
            <el-button type="text" size="mini" @click="handleUser(scope.row)">人员设置</el-button>
            <!-- <el-button type="text" size="mini" @click="handleDetail(scope.row)">明细</el-button> -->
            <el-button v-if="active === '0'" type="text" size="mini" @click="handleCommodity(scope.row)">
              商品设置</el-button>
            <el-button type="text" size="mini" @click="handleStatistics(scope.row)">活动统计</el-button>
          </template>
        </el-table-column>
      </v-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />

      <el-dialog
        v-el-drag-dialog
        :destroy-on-close="true"
        :visible.sync="visible"
        :close-on-click-modal="false"
        title="新建/编辑福利发放"
        center
        width="800px"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="180px" style="height: 470px">
          <el-form-item label="发放名称" prop="giveName">
            <el-input v-model.trim="form.giveName" placeholder="请输入发放名称" />
          </el-form-item>
          <el-form-item v-show="state == 'create' " label="福利类型" prop="classifType">
            <el-radio-group v-model="form.classifType" @change="changeType">
              <el-radio v-for="(item, index) in types" :key="index" :label="item.id">{{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="form.classifType === '0'">
            <el-form-item label="出金账户" prop="accountId">
              <el-select
                v-model="form.accountId"
                :disabled="state!='create'"
                placeholder="请选择"
                style="width: 100%"
                @change="handleAccChange"
              >
                <el-option
                  v-for="(item, index) in accList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="充值记录" prop="rechargeId">
              <el-select
                v-model="form.rechargeId"
                :disabled="state!='create'"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in rechList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="职工福利子账户类型" prop="classifType2">
              <el-select
                v-model="form.classifType2"
                :disabled="state!='create'"
                placeholder="请选择"
                style="width: 100%"
                @change="handleAccountChange"
              >
                <el-option
                  v-for="(item, index) in accounts"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否支持福利金帐号" prop="isWelfarePay">
              <el-radio-group v-model="form.isWelfarePay">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="定向发放金额(每人)上限" prop="userUpperLimit">
              <el-input
                v-model="form.userUpperLimit"
                oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
                placeholder="请输入定向发放金额(每人)上限"
                @blur="myBlur"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="福利领取起止时间" required>
              <el-col :span="11">
                <el-form-item label prop="receiveStarttime">
                  <el-date-picker
                    v-model="form.receiveStarttime"
                    type="datetime"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label prop="receiveEndtime">
                  <el-date-picker
                    v-model="form.receiveEndtime"
                    type="datetime"
                    placeholder="选择结束日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="福利使用起止时间" required>
              <el-col :span="8">
                <el-form-item label prop="expirationStartdate">
                  <el-date-picker
                    v-model="form.expirationStartdate"
                    :disabled="fit"
                    type="datetime"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="1">-</el-col>
              <el-col :span="8">
                <el-form-item label prop="expirationDate">
                  <el-date-picker
                    v-model="form.expirationDate"
                    :disabled="fit"
                    type="datetime"
                    placeholder="选择结束日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="7">
                <el-checkbox v-model="fit" @change="setEqualTime">与福利领取时间一致</el-checkbox>
              </el-col>
            </el-form-item>
            <el-form-item label="专区名称" prop="areaName">
              <el-input v-model.trim="form.areaName" placeholder="请输入专区名称" />
            </el-form-item>
            <el-form-item label="专区图片" prop="areaImg">
              <image-upload
                ref="upload4home"
                :key="upload4area.imagecropperKey"
                v-model="form.areaImg"
                :preview-id="upload4area.viewId"
                :forever="true"
                :width="705"
                :view="upload4area.view"
                :height="350"
                :no-circle="true"
                :no-rotate="false"
                lang-type="zh"
                :max-size="200"
              />
            </el-form-item>
            <el-form-item label="首页图片" prop="homeImg">
              <image-upload
                ref="upload4home"
                :key="upload4home.imagecropperKey"
                v-model="form.homeImg"
                :preview-id="upload4home.viewId"
                :forever="true"
                :width="702"
                :view="upload4home.view"
                :height="246"
                :no-circle="true"
                :no-rotate="false"
                lang-type="zh"
                :max-size="200"
              />
            </el-form-item>
            <el-form-item label>
              <section class="inner-explain">
                <section>
                  <i
                    class="el-icon-warning-outline"
                  />专区名称、专区图片、首页图片是商城中该福利活动的展示配置。专区图片是封面图，首页图片用于专区详情页。
                </section>
              </section>
            </el-form-item>
          </template>
          <template v-else-if="form.classifType === '1'">
            <el-form-item label="兑换券" prop="classifType2">
              <el-select
                v-model="form.classifType2"
                :disabled="state!='create'"
                placeholder="请选择"
                style="width: 100%"
                @change="handleCouponsChange"
              >
                <el-option
                  v-for="(item, index) in couponsList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="兑换券领取起止时间" prop="receiveStarttime">
              <el-col :span="11">
                <el-form-item label prop="receiveStarttime">
                  <el-date-picker
                    v-model="form.receiveStarttime"
                    type="datetime"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label prop="receiveEndtime">
                  <el-date-picker
                    v-model="form.receiveEndtime"
                    type="datetime"
                    placeholder="选择结束日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="兑换券使用起止时间" prop="expirationStartdate">
              <el-col :span="11">
                <el-form-item label prop="expirationStartdate">
                  <el-date-picker
                    v-model="form.expirationStartdate"
                    disabled
                    type="datetime"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label prop="expirationDate">
                  <el-date-picker
                    v-model="form.expirationDate"
                    disabled
                    type="datetime"
                    placeholder="选择结束日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
            </el-form-item>
          </template>
          <template v-else-if="form.classifType === '7'">
            <el-form-item label="商城商户" prop="dataId">
              <el-select
                v-model="form.dataId"
                :disabled="state!='create'"
                placeholder="请选择"
                style="width: 100%"
                @change="closeTag"
              >
                <el-option
                  v-for="(item, index) in merchantList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="兑换券" prop="classifType2">
              <!-- 	<el-select :disabled="state!='create'" v-model="form.classifType2" placeholder="请选择"
								style="width: 100%" @change="handleCouponsChange2">
								<el-option v-for="(item, index) in mallCoupons" :key="index" :label="item.label"
									:value="item.value" />
							</el-select> -->
              <el-tag v-if="form.classifType2" :closable="state=='create'" @close="closeTag()">{{ form.areaName }}</el-tag>
              <el-button v-else class="button-new-tag" size="small" @click="showTable">选择优惠券</el-button>
            </el-form-item>
            <el-form-item label="兑换券领取起止时间" prop="receiveStarttime">
              <el-col :span="11">
                <el-form-item label prop="receiveStarttime">
                  <el-date-picker
                    v-model="form.receiveStarttime"
                    type="datetime"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label prop="receiveEndtime">
                  <el-date-picker
                    v-model="form.receiveEndtime"
                    type="datetime"
                    placeholder="选择结束日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="兑换券使用起止时间" prop="expirationStartdate">
              <el-col :span="11">
                <el-form-item label prop="expirationStartdate">
                  <el-date-picker
                    v-model="form.expirationStartdate"
                    disabled
                    type="datetime"
                    placeholder="选择开始日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col style="text-align: center" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item label prop="expirationDate">
                  <el-date-picker
                    v-model="form.expirationDate"
                    disabled
                    type="datetime"
                    placeholder="选择结束日期"
                    style="width: 100%"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
            </el-form-item>
          </template>
          <el-form-item label="使用说明" prop="explain">
            <el-input
              v-model="form.explain"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 6 }"
              placeholder="请输入使用说明"
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="default" style="padding: 10px 30px" @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        v-el-drag-dialog
        :destroy-on-close="true"
        :close-on-click-modal="false"
        width="800px"
        title="选择兑换券"
        center
        :visible.sync="innerVisible"
        append-to-body
      >
        <el-table v-loading="dlistLoading" style="height: 400px" :data="mallCoupons">
          <el-table-column property="couponId" label="优惠券模板ID" />
          <el-table-column property="couponName" label="优惠券名称" />
          <el-table-column property="couponState" :formatter="getState" label="优惠券状态" />
          <el-table-column
            label="操作"
            width="50"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="chooseOne(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="dtotal > 0"
          :total="dtotal"
          :page.sync="dquery.page"
          :limit.sync="dquery.pageSize"
          @pagination="getMallCoupons('d')"
        />
      </el-dialog>
    </section>
  </section>
</template>
<script>
import {
  int
} from '@/utils/validate'
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import {
  getJdRech,
  queryJd,
  getRechOne,
  getRech,
  getDictByCode,
  queryPage,
  insert4Account,
  update4Account,
  insert4Coupon,
  update4Coupon,
  updatePublishStatus,
  get,
  del,
  queryAccount,
  queryCoupons,
  getAcc,
  queryMerchant,
  merchantCoupons
} from './../api/grant'
import permission from '@/directive/permission/index.js'
import elDragDialog from '@/directive/el-drag-dialog'
import ImageUpload from '@/components/ImageUpload'
import CryptoJS from '@/utils/aesJiaJM'
export default {
  name: 'GrantMain',
  components: {
    Pagination,
    VTable,
    ImageUpload
  },
  directives: {
    permission,
    elDragDialog
  },
  data() {
    return {
      dlistLoading: false,
      dquery: {
        page: 1,
        pageSize: 10
      },
      dtotal: 0,
      innerVisible: false,
      i: '',
      listQuery: {
        page: 1,
        limit: 10,
        giveName: ''
      },
      list: [],
      accList: [],
      rechList: [],
      total: 0,
      listLoading: false,
      multipleSelection: [],
      merchantList: [],
      mallCoupons: [],
      visible: false,
      form: {
        id: '',
        accountId: '',
        rechargeId: '',
        giveName: '',
        userUpperLimit: '',
        classifType: '0',
        classifType2: '',
        receiveStarttime: '',
        receiveEndtime: '',
        expirationStartdate: '',
        expirationDate: '',
        explain: '',
        // publishStatus: 'GIPSTSTUS02',
        areaName: '',
        areaImg: '',
        homeImg: '',
        dataId: '',
        isWelfarePay: 1,
        dataType: ''
      },
      rules: {
        dataId: [{
          required: true,
          message: '请选择商城商户',
          trigger: 'change'
        }],
        classifType: [{
          required: true,
          message: '请选择福利类型',
          trigger: 'blur'
        }],
        accountId: [{
          required: true,
          message: '请选择出金账户',
          trigger: 'change'
        }],
        rechargeId: [{
          required: true,
          message: '请选择充值记录',
          trigger: 'change'
        }],
        classifType2: [{
          required: true,
          message: '请选择职工福利子账户类型',
          trigger: 'blur'
        }],
        receiveStarttime: [{
          required: true,
          message: '请选择开始日期',
          trigger: 'blur'
        }],
        receiveEndtime: [{
          required: true,
          message: '请选择结束日期',
          trigger: 'blur'
        }],
        giveName: [{
          required: true,
          message: '请输入发放名称',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 50,
          message: '长度在 1 到 50 个字符',
          trigger: 'blur'
        }
        ],
        areaName: [{
          required: true,
          message: '请输入专区名称',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 50,
          message: '长度在 1 到 50 个字符',
          trigger: 'blur'
        }
        ],
        areaImg: [{
          required: true,
          message: '请上传专区图片',
          trigger: 'blur'
        }],
        homeImg: [{
          required: true,
          message: '请上传首页图片',
          trigger: 'blur'
        }],
        isWelfarePay: [{
          required: true,
          message: '请选择是否支持福利金帐号',
          trigger: 'blur'
        }],
        userUpperLimit: [{
          required: true,
          message: '请输入定向发放金额(每人)上限',
          trigger: 'blur'
        }
          // { validator: int, trigger: 'blur' }
        ],
        explain: [{
          required: true,
          message: '请填写使用说明',
          trigger: 'blur'
        }],
        expirationStartdate: [{
          required: true,
          message: '请选择开始日期',
          trigger: 'blur'
        }],
        expirationDate: [{
          required: true,
          message: '请选择结束日期',
          trigger: 'blur'
        }]
      },
      upload4area: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      upload4home: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      types: [{
        name: '福利包',
        id: '0'
      },
      {
        name: '兑换券',
        id: '1'
      },
      {
        name: '线下提货券',
        id: '7'
      }
      ],
      accounts: [],
      couponsList: [], // 兑换券列表
      jdList: [], // 京东活动
      active: '0',
      fit: true,
      state: 'create'
    }
  },
  watch: {
    'form.receiveStarttime': {
      handler(newName, oldName) {
        if (this.form.classifType === '1') {
          return
        }

        if (newName && this.fit) {
          this.form.expirationStartdate = this.form.receiveStarttime
        }
      },
      immediate: true,
      deep: true
    },
    'form.receiveEndtime': {
      handler(newName, oldName) {
        if (this.form.classifType === '1') {
          return
        }
        if (newName && this.fit) {
          this.form.expirationDate = this.form.receiveEndtime
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    if (this.$route.query.t) {
      this.active = this.$route.query.t
    }
    this.getList()
  },
  methods: {
    setEqualTime(val) {
      if (val) {
        this.form.expirationStartdate = this.form.receiveStarttime
        this.form.expirationDate = this.form.receiveEndtime
      }
    },
    closeTag() {
      this.form.classifType2 = ''
      this.form.areaName = ''
    },
    chooseOne(row) {
      this.form.classifType2 = row.couponId
      this.form.areaName = row.couponName
      this.innerVisible = false
    },
    getState(row, tag) {
      const t = row[tag]
      let text = '正常'
      switch (t) {
        case '01':
          text = '过期'
          break
        case '02':
          text = '作废'
          break
        case '03':
          text = '未生效'
          break
        case '04':
          text = '以转增'
          break
      }
      return text
    },
		 async showTable() {
      if (this.form.dataId == '') {
        this.$message.error('请选择商城商户')
        return
      }
      this.dquery.page = 1
      this.dquery.pageSize = 10
      this.dtotal = 0
      await this.getMallCoupons('d')
      this.innerVisible = true
    },
    getMallCoupons(t) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        const query = {
          merchantId: this.form.dataId
        }
        if (t == 'd') {
          query.page = this.dquery.page,
          query.pageSize = this.dquery.pageSize
        }
        merchantCoupons(query).then(res => {
          loading.close()
          const arr = res.data.data.data || []
          this.mallCoupons = res.data.data.data || []
          this.dtotal = res.data.data.total || 0
          resolve(arr)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    myBlur(e) {
      this.form.userUpperLimit = e.target.value
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'y+': date.getFullYear().toString(), // 年
        'M+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'm+': date.getMinutes().toString(), // 分
        's+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
        }
      }
      return fmt
    },
    /**
			 * 切换福利类型
			 */
    async changeType(val) {
      if (val == 0) {
        this.form.dataType = ''
        this.accList = await this.getAccFun()
        this.getAccounts().then((res) => {
          if (res.length > 0) {

          } else {
            this.$message({
              title: '提示',
              message: '当前无可用职工福利子账户，请前往【福利中心--账号管理--职工福利子账户管理】创建职工福利子账户。',
              type: 'error',
              duration: 2000
            })
          }
        }).catch(err => {
          console.log(err)
        })
      } else if (val == 1) {
        this.form.dataType = ''
        this.couponsList = await this.getCoupons()
      } else if (val == 7) {
        this.form.dataType = ''
        this.getMallAccounts().then((res) => {
          if (res.length > 0) {

          } else {
            this.$message({
              title: '提示',
              message: '当前无可用商城商户，请前往【福利中心--福利配置--平台商城商户管理】创建商城商户。',
              type: 'error',
              duration: 2000
            })
          }
        }).catch(err => {
          console.log(err)
        })
      }
      const arr = ['id', 'giveName', 'classifType', 'explain', 'dataType']
      for (const i in this.form) {
        if (arr.indexOf(i) === -1) {
          this.form[i] = ''
        }
      }
      this.fit = val !== '1'
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    filtercolumn(scope, item) {
      if (item === 'receiveTime') {
        return (scope.row['receiveStarttime'] && scope.row['receiveStarttime'].substring(0, 10)) + '至' + (scope
          .row['receiveEndtime'] && scope.row['receiveEndtime'].substring(0, 10))
      } else if (item === 'expirationTime') {
        let str = ''
        if (scope.row['expirationStartdate'] && scope.row['expirationStartdate'] != undefined) {
          str += scope.row['expirationStartdate'].substring(0, 10)
        }
        if (scope.row['expirationDate'] && scope.row['expirationDate'] != undefined) {
          str += '至' + scope.row['expirationDate'].substring(0, 10)
        }
        return str
      } else if (item === 'classifType2') {
        return scope.row[item] || '--'
      } else {
        return scope.row[item]
      }
    },

    /**
			 * 选项卡切换
			 */
    handleTabClick(tab, event) {
      this.listQuery.page = 1
      this.getList()
    },
    /**
			 * 选项卡切换2
			 */
    handleTabClick2(item) {
      this.active = item.id
      this.listQuery.page = 1
      this.getList()
    },

    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },

    handleAccountChange(value) {
      const obj = this.accounts.find(a => a.subAcntTp === value)
      this.$alert(`您选择的付款子帐户是：${obj.subAcntNm}，状态为：${obj.subAcntSt == 1 ? '禁用' : '启用'}，
        ${obj.subAcntStartTm ? '有效期是：' + this.formatTime(obj.subAcntStartTm) + '至' : ''}
        ${obj.subAcntEndTm ? this.formatTime(obj.subAcntEndTm) + ']' : ''}`, '提示', {
        confirmButtonText: '确定'
      })
    },
    async handleAccChange(val) {
      this.form.rechargeId = ''
      this.rechList = await this.getRechList(val)
    },

    handleCouponsChange(value) {
      const obj = this.couponsList.find(a => a.id === value)
      this.$alert(`您选择的兑换券是：${obj.name}，兑换券数量为：${obj.total}，审核状态为：${obj.auditStatusValue}，使用状态为：${obj.statusValue}，
        ${obj.startUseTime ? '有效期是：' + this.formatTime(obj.startUseTime) + '至' : ''}
        ${obj.endUseTime ? this.formatTime(obj.endUseTime) + ']' : ''}`, '提示', {
        confirmButtonText: '确定',
        callback: action => {
          this.form.expirationStartdate = obj.startUseTime
          this.form.receiveStarttime = obj.startUseTime
          this.form.expirationDate = obj.endUseTime
          this.form.receiveEndtime = obj.endUseTime
        }
      })
    },
    handleCouponsChange2(value) {},
    handleReset() {
      this.listQuery.page = 1
      this.listQuery.giveName = ''
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleCreate() {
      for (const key in this.form) {
        if (key === 'publishStatus') {
          this.form[key] = 'GIPSTSTUS02'
        } else if (key === 'isWelfarePay') {
          this.form[key] = 1
        } else {
          this.form[key] = ''
        }
      }
      this.upload4home.viewId = ''
      this.upload4area.viewId = ''
      this.rechList = []
      this.mallCoupons = []
      this.merchantList = []
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.state = 'create'
      this.visible = true
    },

    handleUpdate(row) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(row.id).then(async res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if (key === 'areaImg') {
              this.form[key] = data[key]
              this.upload4area.viewId = data[key]
            } else if (key === 'homeImg') {
              this.form[key] = data[key]
              this.upload4home.viewId = data[key]
            } else {
              this.form[key] = data[key]
            }
          }
          this.fit = this.form.receiveStarttime === this.form.expirationStartdate && this.form.receiveEndtime === this.form.expirationDate
          this.state = 'update'
          if (this.form.classifType == '0') {
            this.accList = await this.getAccFun()
            this.rechList = await this.getRechOneFun(this.form.rechargeId)
            this.getAccounts().then(() => {
              this.visible = true
              this.$nextTick(() => {
                this.$refs['form'].clearValidate()
              })
            })
          } else if (this.form.classifType == '1') {
            this.couponsList = await this.getCoupons()
            this.visible = true
            this.$nextTick(() => {
              this.$refs['form'].clearValidate()
            })
          } else if (this.form.classifType == '7') {
            this.getMallAccounts().then((res) => {
              if (res.length > 0) {
                // this.handleMerchantChange(this.form.dataId)
                this.visible = true
                this.$nextTick(() => {
                  this.$refs['form'].clearValidate()
                })
              } else {
                this.$message({
                  title: '提示',
                  message: '当前无可用商城商户，请前往【福利中心--福利配置--平台商城商户管理】创建商城商户。',
                  type: 'error',
                  duration: 2000
                })
              }
            }).catch(err => {
              console.log(err)
            })
          }
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },

    handleStatus(row) {
      const state = row.publishStatus === 'GIPSTSTUS01' ? 'GIPSTSTUS02' : 'GIPSTSTUS01'
      let msg = ''
      if (row.publishStatus === 'GIPSTSTUS01') {
        msg = '取消发布'
      } else {
        msg = '发布'
      }
      this.$confirm('确定' + msg + '该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          updatePublishStatus({
            id: row.id,
            publishStatus: state
          }).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: msg + '成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => {})
    },

    handleUser(row) {
      this.$router.push({
        path: this.$filterPath('user'),
        query: {
          id: row.id,
          t: this.active
        }
      })
    },

    handleCommodity(row) {
      this.$router.push({
        path: this.$filterPath('commodity'),
        query: {
          id: row.id,
          t: this.active
        }
      })
    },
    handleStatistics(row) {
      const fromObj = {
        from: '/welfare/grants/grant/index',
        t: this.active
      }
      const path = this.active === '0' || this.active === '1' ? this.$filterPath('activitystatistics4fy') : this.$filterPath('activitystatistics')
      // sessionStorage.setItem("curPath","/welfare/grants/grant/")
      this.$router.push({
        path: path,
        query: {
          id: row.id,
          couponMallId: row.couponMallId || '', // 兑换券统计要把兑换券的id传到下一页
          from: JSON.stringify(fromObj),
          c: row.classifType
        }
      })
    },

    handleDetail(row) {
      this.$router.push({
        path: this.$filterPath('detail'),
        query: {
          id: row.id,
          t: this.active
        }
      })
    },

    handleDelete(ids) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          del(ids).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => {})
    },

    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0]
            .list : []
        }).catch(error => {
          reject(error)
        })
      })
    },

    formatTime(str) {
      return str && str.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
    },
    getRechList(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getRech({
          accountId: id
        }).then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.applyName}(${a.rechargeAmount}元)`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getRechOneFun(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getRechOne({
          rechargeId: id
        }).then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.applyName}(${a.rechargeAmount}元)`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getCoupons() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        queryCoupons({
          auditStatus: 'COUPONAUSTATUS03'
        }).then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.name}-${a.total}[${a.statusValue}]${a.startUseTime ? '[' + this.formatTime(a.startUseTime) + '至' : ''}${a.endUseTime ? this.formatTime(a.endUseTime) + ']' : ''}`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getAccFun() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getAcc().then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.name}(${CryptoJS.$aesJieM(a.accountNumber)})`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getAccounts() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        queryAccount({
          giveInfoId: this.form.id
        }).then(res => {
          loading.close()
          const arr = res.data.data || []
          this.accounts = arr.map(a => ({
            ...a,
            value: a.subAcntTp,
            label: `${a.subAcntTp}-${a.subAcntNm}[${a.subAcntSt == 1 ? '禁用' : '启用'}]${a.subAcntStartTm ? '[' + this.formatTime(a.subAcntStartTm) + '至' : ''}${a.subAcntEndTm ? this.formatTime(a.subAcntEndTm) + ']' : ''}`
          }))
          resolve(arr)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getMallAccounts() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        queryMerchant().then(res => {
          loading.close()
          const arr = res.data.data || []
          this.merchantList = arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.merchantName}-${a.merchantNumber}[${a.statusValue}]`
          }))
          resolve(arr)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    submit() {
      if (this.form.classifType === '0') {
        if (new Date(this.form.receiveEndtime).getTime() < new Date().getTime()) {
          this.$message({
            message: '福利领取结束时间不得小于当前时间！',
            type: 'warning'
          })
          return
        }
        if (new Date(this.form.expirationDate).getTime() < new Date().getTime()) {
          this.$message({
            message: '福利使用结束时间不得小于当前时间！',
            type: 'warning'
          })
          return
        }
        if (new Date(this.form.receiveStarttime).getTime() > new Date(this.form.receiveEndtime).getTime()) {
          this.$message({
            message: '福利领取开始时间不得大于福利领取结束时间！',
            type: 'warning'
          })
          return
        }
        if (new Date(this.form.expirationStartdate).getTime() > new Date(this.form.expirationDate).getTime()) {
          this.$message({
            message: '福利使用开始时间不得大于福利使用结束时间！',
            type: 'warning'
          })
          return
        }
        if (new Date(this.form.expirationStartdate).getTime() < new Date(this.form.receiveStarttime).getTime()) {
          this.$message({
            message: '福利使用开始时间不得小于福利领取开始时间！',
            type: 'warning'
          })
          return
        }
        if (new Date(this.form.expirationDate).getTime() < new Date(this.form.expirationStartdate).getTime()) {
          this.$message({
            message: '福利使用结束时间不得小于福利领取结束时间！',
            type: 'warning'
          })
          return
        }
        this.state == 'create' ? this.createData4Accounts(this.form.classifType) : this.updateData4Accounts()
      } else if (this.form.classifType === '1') {
        if (new Date(this.form.receiveEndtime).getTime() < new Date().getTime()) {
          this.$message({
            message: '兑换券领取结束时间不得小于当前时间！',
            type: 'warning'
          })
          return
        }
        if (new Date(this.form.expirationDate).getTime() < new Date().getTime()) {
          this.$message({
            message: '兑换券已过期，请选择其他兑换券！',
            type: 'warning'
          })
          return
        }
        this.state == 'create' ? this.createData4Coupon(this.form.classifType) : this.updateData4Coupon()
      } else if (this.form.classifType === '7') {
        if (new Date(this.form.receiveEndtime).getTime() < new Date().getTime()) {
          this.$message({
            message: '活动开始结束时间不得小于当前时间！',
            type: 'warning'
          })
          return
        }
        if (new Date(this.form.expirationDate).getTime() < new Date().getTime()) {
          this.$message({
            message: '活动已结束，请选择其他活动！',
            type: 'warning'
          })
          return
        }
        this.form.userUpperLimit = 1
        this.state == 'create' ? this.createData4Coupon(this.form.classifType) : this.updateData4Coupon()
      }
    },
    createData4Accounts() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          return new Promise((resolve, reject) => {
            insert4Account(params).then(() => {
              this.dialogVisible = false
              loading.close()
              this.$message({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.active = params.classifType
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },

    updateData4Accounts() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          params['bigturntableId'] = this.id
          return new Promise((resolve, reject) => {
            update4Account(params).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },

    createData4Coupon(type) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (new Date(this.form.receiveEndtime).getTime() > new Date(this.form.expirationDate)
            .getTime()) {
            this.$message({
              title: '提示',
              message: '兑换券领取结束时间不得大于兑换券使用结束时间',
              type: 'error',
              duration: 2000
            })
            return
          }
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          return new Promise((resolve, reject) => {
            insert4Coupon(params, type).then(() => {
              this.dialogVisible = false
              loading.close()
              this.$message({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.active = params.classifType
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },

    updateData4Coupon() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (new Date(this.form.receiveEndtime).getTime() > new Date(this.form.expirationDate)
            .getTime()) {
            this.$message({
              title: '提示',
              message: '兑换券领取结束时间不得大于兑换券使用结束时间',
              type: 'error',
              duration: 2000
            })
            return
          }
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          params['bigturntableId'] = this.id
          return new Promise((resolve, reject) => {
            update4Account(params).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },
    getList(obj) {
      this.listLoading = true
      var query = {
        classifType: this.active,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        giveName: this.listQuery.giveName
      }
      return new Promise((resolve, reject) => {
        queryPage(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    }
  }
}
</script>
<style lang="scss">
	@import '@/styles/mixin.scss';

	.grant-main {
		padding: 10px;

		.main-search {
			background-color: #fff;
			padding: 0 10px;

			.svg-container {
				padding: 0 5px 0 10px;
				color: #bfced6;
				vertical-align: middle;
				display: inline-block;
			}

			.search-input {
				width: 60%;
				position: relative;

				&:after {
					content: '';
					position: absolute;
					left: -25px;
					right: 0;
					bottom: 8px;
					height: 1px;
					background: rgba(226, 227, 232, 1);
				}

				input {
					outline: none;
					background: transparent;
					border: none;
					outline: medium;
					padding: 0;

					&:focus {
						outline: none;
						background-color: transparent;
					}
				}
			}

			.search-btn {
				display: inline-block;
				float: right;

				.el-button.is-round {
					padding: 10px 30px;
					margin-right: 34px;
				}

				.search-more {
					font-size: 14px;
					font-weight: 500;
					@include font-color($mainColor);
					cursor: pointer;
					margin-left: 10px;
				}
			}

			&.merge {
				height: 50px;
				line-height: 50px;
			}
		}

		.main-buttons {
			display: flex;
			line-height: 36px;
			margin-top: 10px;

			.main-buttons-title {
				flex: 1;
				height: 36px;
				line-height: 36px;
				font-size: 16px;
				font-weight: bold;
				color: rgba(51, 51, 51, 1);
			}
		}

		.main-tab {
			width: 100%;
			margin-top: 10px;
			padding: 0 10px;
			background-color: #fff;
			display: flex;
			border-radius: 4px;
			// .tabs{
			// 	height: 60px;
			// 	display: flex;
			// 	font-family: Helvetica Neue,Helvetica,PingFang SC,Hiragino Sans GB,Microsoft YaHei,SimSun,sans-serif;
			// 	.tabItem{
			// 		 display: flex;
			// 		 align-items:center;
			// 		 height: 100%;
			// 		 margin-right: 20px;
			// 		 cursor: pointer;
			// 		 @include font-color($mainColor);
			// 		 &.leng{
			// 			 width: 70px;
			// 		 }
			// 		 &.choose{
			// 			 position: relative;
			// 			 height: 100%;
			// 			 &::before{
			// 					position: absolute;
			// 					content: '';
			// 					bottom: 0px;
			// 					left: 0;
			// 					right: 0;
			// 					top: 0;
			// 					border-bottom:2px solid $mainColor ;
			// 			 }
			// 		 }

			// 	}
			// }
			.el-tabs__nav-wrap::after {
				display: none;
			}

			.el-tabs__header {
				margin: 0;
			}
		}

		.inner-explain {
			margin-top: 10px;
			line-height: 1.1;
			color: #999;
			font-size: 14px;
			display: flex;
			align-items: flex-start;

			>i {
				margin-right: 5px;
			}

			p {
				margin: 0;
				padding: 0;
				margin-bottom: 5px;
			}
		}
	}
</style>
